//
//  BHMyFunlistViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/30.
//

import UIKit

class BHMyFunlistViewController: BHBaseViewController {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.sectionInset = .zero
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.register(UINib.init(nibName: "BHMoreFunCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHMoreFunCollectionViewCell")
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        
        return view
    }()

    fileprivate var funArray: [BHFunListInfoModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "我的趣玩"

        self.view.addSubview(self.collectionView)
        
        self.loadFunService()
        
        self.collectionView.addRefresh { [weak self] in
            self?.page = 1
            self?.loadFunService()
        }
        
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            self?.loadFunService()
        }
    }


}
extension BHMyFunlistViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.funArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.width, height: BHMoreFunCollectionViewCell.moreFunHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.funArray[indexPath.row]
        let detailVC = BHMyFunDetailViewController.init()
        detailVC.funApplyType = model.createFlag
        detailVC.funId = model.funId
        BHNavigationController.currentNavigationController?.pushViewController(detailVC, animated: true)
        detailVC.refreshFunListBlock = { [weak self] in
            self?.page = 1
            self?.loadFunService()
        }
    }
    
}

extension BHMyFunlistViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHMoreFunCollectionViewCell", for: indexPath) as! BHMoreFunCollectionViewCell
        let model = self.funArray[indexPath.row]
        cell.model = model
        return cell
    }
    
    
}

extension BHMyFunlistViewController {
    func loadFunService()  {
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.me_fun_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.collectionView.endRefresh()
            self.collectionView.endLoading()
            
            if success == true {
                let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")

                if self.page == 1 {
                    self.collectionView.endLoadWithNoMoreData(false)
                    if self.funArray.count != 0 {
                        self.funArray.removeAll()
                    }
                }
                
                let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
                for dic in record {
                    let model = BHFunListInfoModel.init()
                    model.parseDic(dic as! [String : Any])
                    self.funArray.append(model)
                }
                self.collectionView.reloadData()
                if self.funArray.count >= total {
                    self.collectionView.endLoadWithNoMoreData(true)
                }
                    
            }else {
                BHToast.toast(text: errorMsg) 
            }
        }
        
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 10
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        
        return dic
    }
}
